package io.gps.datatransfer.task;

import io.gps.datatransfer.CenterChannel;
import io.gps.datatransfer.utils.SysDef;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import java.util.Map;

public class ScheduleCloseTcpSessionTask implements Runnable {

    private Logger logger = Logger.getLogger(ScheduleCloseTcpSessionTask.class);

    @Override
    public void run() {
        try {
            if (!SysDef.sim_session.isEmpty()) {
                int index = 0;
                for (Map.Entry<String, IoSession> entry : SysDef.sim_session.entrySet()) {
                    if(SysDef.UP_SERVER!=null){
                        for (int i = 0; i < SysDef.UP_SERVER.size(); i++) {
                            if(SysDef.UP_SERVER.get(i)!=null){
                                String tempkey=SysDef.getserverkey(entry.getKey(),SysDef.UP_SERVER.get(i).getServerid());
                                CenterChannel center = SysDef.sim_server_center.get(tempkey);
                                if(entry.getValue()!=null){
                                    if(entry.getValue().isConnected()&&(System.currentTimeMillis()-entry.getValue().getLastReadTime()<600000)){
                                        if(center==null||center.getDevServer().getServerid()==null){
                                            center=new CenterChannel(SysDef.UP_SERVER.get(i),entry.getKey());
                                            SysDef.sim_server_center.put(tempkey,center);
                                        }
                                    }else{
                                        if(center!=null){
                                            center.disconnectALL("ScheduleCloseTcpSessionTask 定时检查回收");
                                        }
                                    }
                                }
                            }
                        }
                        if(entry.getValue().isConnected()&&(System.currentTimeMillis()-entry.getValue().getLastReadTime()<600000)){
                            index++;
                            entry.getValue().closeNow();
                        }
                    }
                }
                logger.error("ScheduleCloseTcpSessionTask : close TCP session sum" + index);
            }
        } catch (Exception e) {
            logger.error("ScheduleCloseTcpSessionTask : close TCP session ERROR!", e);
        }
    }
}
